﻿package com.toncen.samepms.basic.dao;

import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.toncen.samepms.basic.action.DocumentsUploadAction;
import com.toncen.samepms.basic.domain.DocumentsUpload;
import com.toncen.samepms.common.AbstractDao;
import com.sky.common.file.FileUtils;
import com.sky.common.json.JSONUtils;

/**
 * 描述：附件管理表BASIC_DOCUMENTS_UPLOAD的dao文件
 * 
 * @author tch
 */
public class DocumentsUploadDao extends AbstractDao<DocumentsUpload> {

	public DocumentsUploadDao() {
	}

	public String tempFileDir = "D:\\ComitWebFrame\\"; // 临时文件目录

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.comit.common.db.BaseDao#initialize()
	 */
	@Override
	protected void initialize() {
		setStatementPrefix("DocumentsUpload");
		setStatementDivision(".");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.toncen.samepms.common.AbstractDao#delete(long) 删除附件信息表，及对应附件关系表中的数据
	 */
	@Override
	public int delete(long id) throws Exception {
		DocumentsUpload documentsUpload = super.find(id);// 通过主键获取对象
		if (documentsUpload != null && null != documentsUpload.getDocumentRelation()) {// 删除从表中的数据
			DocumentRelationDao drDao = new DocumentRelationDao();
			drDao.delete(documentsUpload.getDocumentRelation());
			String filePath = getAllFilePath(documentsUpload);
			File file = new File(filePath);
			file.delete();// 删除文件
		}
		return super.delete(id);
	}

	/**
	 * @param documentsUpload
	 * @return
	 * @throws Exception
	 *             获取文件全路径
	 */
	public String getAllFilePath(DocumentsUpload documentsUpload) throws Exception {
		String filePath = "";// 文件存放路径
		DocumentsUploadAction du = new DocumentsUploadAction();
		String capability = documentsUpload.getDocumentRelation().getCapability();
		String modelName = capability.substring(capability.lastIndexOf(".") + 1, capability.length()).replace("Action", "");
		filePath = du.getResourceFilePath() + "\\" + modelName + "\\" + documentsUpload.getDocumentRelation().getRecodeId() + "\\"
				+ documentsUpload.getFileName();
		filePath = FileUtils.getStandardFilePath(filePath);
		return filePath;
	}

	/**
	 * 
	 * TODO查出附件信息
	 * 
	 * capability:actionClassName,recodeId:domainId,fileType:文件类型
	 * 
	 * @author May 23, 2012 12:11:32 PM ZQ
	 * @param map
	 * @return
	 * @throws SQLException
	 * 
	 */
	public List<DocumentsUpload> getByDomain(Map<String, Object> map) throws SQLException {
		return getSqlMap().queryForList(getStatement("getByDomain"), map);
	}

	public static void main(String[] args) throws SQLException {
		DocumentsUploadDao dao = new DocumentsUploadDao();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("capability", "com.toncen.samepms.demo.action.DemoFatherAction");
		map.put("recodeId", "1337147648571");
		map.put("fileType", "1");

		List<DocumentsUpload> list = dao.getByDomain(map);
		System.out.println(JSONUtils.object2JSON(list));
	}
}
